import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Card, message, Spin, Row, Col, Switch, InputNumber, Table, Modal, Popconfirm, Select } from 'antd';
import { PlusOutlined, SearchOutlined } from '@ant-design/icons';
import { getAllBookingSettings, createBookingSetting, updateBookingSetting, deleteBookingSetting } from '@/services/bookingSetting';
import { getStores } from '@/services/store';

const { Option } = Select;

const BookingSetting = () => {
  const [form] = Form.useForm();
  const [searchForm] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [settings, setSettings] = useState([]);
  const [stores, setStores] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingSetting, setEditingSetting] = useState(null);

  useEffect(() => {
    fetchBookingSettings();
    fetchStores();
  }, []);

  const fetchStores = async () => {
    try {
      const res = await getStores({ pageSize: 999 }); // 获取所有门店
      if (res.success) {
        setStores(res.data.list || []);
      } else {
        message.error('获取门店列表失败');
      }
    } catch (error) {
      message.error('获取门店列表失败');
    }
  };

  const fetchBookingSettings = async (params = {}) => {
    setLoading(true);
    try {
      const res = await getAllBookingSettings(params);
      if (res.success) {
        setSettings(res.data || []);
      } else {
        message.error('获取预约配置列表失败');
      }
    } catch (error) {
      message.error('获取预约配置列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = (values) => {
    console.log('Search values:', values); // 添加日志
    fetchBookingSettings(values);
  };

  const handleReset = () => {
    searchForm.resetFields();
    fetchBookingSettings();
  };

  const handleAdd = () => {
    setEditingSetting(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  const handleEdit = (record) => {
    setEditingSetting(record);
    form.setFieldsValue(record);
    setIsModalVisible(true);
  };

  const handleDelete = async (id) => {
    try {
      const res = await deleteBookingSetting(id);
      if (res.success) {
        message.success('删除成功');
        fetchBookingSettings();
      } else {
        message.error('删除失败');
      }
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      let res;
      if (editingSetting) {
        res = await updateBookingSetting({ ...editingSetting, ...values });
      } else {
        res = await createBookingSetting(values);
      }

      if (res.success) {
        message.success(editingSetting ? '更新成功' : '创建成功');
        setIsModalVisible(false);
        fetchBookingSettings();
      } else {
        message.error(editingSetting ? '更新失败' : '创建失败');
      }
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const columns = [
    { title: 'ID', dataIndex: 'id', key: 'id' },
    { title: '门店名称', dataIndex: 'store_id', key: 'store_id', render: (storeId) => stores.find(s => s.id === storeId)?.name || storeId },
    { title: '每日订单数限制', dataIndex: 'order_limit', key: 'order_limit' },
    { title: '可提前取消(分)', dataIndex: 'cancel_before_minutes', key: 'cancel_before_minutes' },
    { title: '允许提前开门', dataIndex: 'allow_early_check_in', key: 'allow_early_check_in', render: (text) => (text ? '是' : '否') },
    { title: '允许改签', dataIndex: 'allow_modify_order', key: 'allow_modify_order', render: (text) => (text ? '是' : '否') },
    { title: '可提前预约天数', dataIndex: 'pre_booking_days', key: 'pre_booking_days' },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <span>
          <Button type="link" onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Popconfirm title="确定删除吗?" onConfirm={() => handleDelete(record.id)}>
            <Button type="link" danger>
              删除
            </Button>
          </Popconfirm>
        </span>
      ),
    },
  ];

  const renderSearchForm = () => (
    <Form form={searchForm} layout="inline" onFinish={handleSearch} style={{ marginBottom: 16 }}>
      <Form.Item name="store_id">
        <Select placeholder="请选择门店" style={{ width: 200 }} allowClear showSearch filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}>
          {stores.map(store => (
            <Option key={store.id} value={store.id}>{store.name}</Option>
          ))}
        </Select>
      </Form.Item>
      <Form.Item>
        <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
          查询
        </Button>
      </Form.Item>
      <Form.Item>
        <Button onClick={handleReset}>重置</Button>
      </Form.Item>
    </Form>
  );

  return (
    <Spin spinning={loading}>
      <Card title="预约规则管理">
        {renderSearchForm()}
        <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd} style={{ marginBottom: 16 }}>
          新增规则
        </Button>
        <Table columns={columns} dataSource={settings} rowKey="id" />
      </Card>

      <Modal
        title={editingSetting ? '编辑预约规则' : '新增预约规则'}
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        destroyOnClose
      >
        <Form form={form} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="门店" name="store_id" rules={[{ required: true, message: '请选择门店' }]}>
                <Select placeholder="请选择门店" style={{ width: '100%' }} showSearch filterOption={(input, option) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}>
                  {stores.map(store => (
                    <Option key={store.id} value={store.id}>{store.name}</Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="用户每日最多可预约订单数" name="order_limit" tooltip="0为不限制">
                <InputNumber min={0} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="迟到自动取消（分钟）" name="late_cancel_minutes">
                <InputNumber min={0} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="可提前取消订单（分钟）" name="cancel_before_minutes">
                <InputNumber min={0} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="可提前开门（分钟）" name="early_check_in_minutes">
                <InputNumber min={0} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="时间段间隔（分钟）" name="time_slot_interval">
                <InputNumber min={0} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="最小计费单位（分钟）" name="min_booking_duration">
                <InputNumber min={0} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="起约时长（小时）" name="min_booking_hours">
                <InputNumber min={1} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="最小延长时长（分钟）" name="max_extend_minutes">
                <InputNumber min={0} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="单个订单最多可更换位置次数" name="max_change_location">
                <InputNumber min={0} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="订单开始前多少分钟不允许改签" name="modify_order_minutes">
                <InputNumber min={0} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="单个订单最多可改签次数" name="max_modify_order_count">
                <InputNumber min={0} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="可提前预约天数" name="pre_booking_days">
                <InputNumber min={0} style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={6}>
              <Form.Item label="允许用户自助取消" name="allow_self_cancel" valuePropName="checked">
                <Switch />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="允许用户提前开门" name="allow_early_check_in" valuePropName="checked">
                <Switch />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="是否允许改签订单" name="allow_modify_order" valuePropName="checked">
                <Switch />
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="是否允许提前离店" name="allow_early_leave" valuePropName="checked">
                <Switch />
              </Form.Item>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col span={6}>
              <Form.Item label="是否可提前预约" name="allow_pre_booking" valuePropName="checked">
                <Switch />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </Spin>
  );
};

export default BookingSetting;